package top.kaoshanji.p2ch11a;

import org.junit.Test;

import java.util.Optional;
import java.util.Properties;

import static org.junit.Assert.assertEquals;

/**
 * author kaoshanji
 * ^_^
 * create time 2025/2/13 19:33
 */
public class ReadPositiveIntParam {

    @Test
    public void testMap() {

        Properties props = new Properties();
        props.setProperty("a", "5");
        props.setProperty("b", "true");
        props.setProperty("c", "-3");

        assertEquals(5, readDurationImperative(props, "a"));
        assertEquals(0, readDurationImperative(props, "b"));
        assertEquals(0, readDurationImperative(props, "c"));
        assertEquals(0, readDurationImperative(props, "d"));

        assertEquals(5, readDurationWithOptional(props, "a"));
        assertEquals(0, readDurationWithOptional(props, "b"));
        assertEquals(0, readDurationWithOptional(props, "c"));
        assertEquals(0, readDurationWithOptional(props, "d"));

    }


    // 代码清单-p2ch11a-259页a：将String转换为Integer，并返回一个Optional对象
    public static Optional s2i(String s) {
        try {
            return Optional.of(Integer.parseInt(s));
        } catch (NumberFormatException e) {
            return Optional.empty();
        }
    }


    // 代码清单-p2ch11a-261页a：以命令式编程的方式从属性中读取 duration 值
    public static int readDurationImperative(Properties props, String name) {
        String value = props.getProperty(name);
        if (value != null) {
            try {
                int i = Integer.parseInt(value);
                if (i > 0) {
                    return i;
                }
            } catch (NumberFormatException e) {}
        }

        return 0;
    }

    // 代码清单-p2ch11a-261页b：使用Optional从属性中读取duration
    public static int readDurationWithOptional(Properties props, String name) {
        /*return Optional.ofNullable(props.getProperty(name))
                .flatMap(ReadPositiveIntParam::s2i)
                .filter(i -> {i > 0}).orElse(0);*/
        return 0;
    }

}
